Java 若要將浮點數,也就是原始型別為 float 或 double 的小數點部分做四捨五入,無條件進位及無條件捨去的做法如下。
使用java.lang.Math類
round()為四捨五入
ceil()為無條件進位
floor()為無條件捨去
請見以下範例,注意 round() 的返回值型態為 long。
double a = 1.999;
Math.round(a); // 2
Math.ceil(a); // 2.0
Math.floor(a); // 1.0
float b = 1.999f;
Math.round(b); // 2
Math.ceil(b); // 2.0
Math.floor(b); // 1.0
如果要指定進位的小數點後指定位數,則先把原本要進位的數乘上10的指定位數方的 double 值,然後再除以該 double 值。
例如要四捨五入,無條件進位,無條件捨去至小數點後2位數,則把原本要進位的數乘上102 double 也就是100.0,然後再除以100.0。
double d = 1.234;
Math.round(d * 1.0) / 1.0; // 1.0 四捨五入至小數點後 0 位
Math.round(d * 10.0) / 10.0; // 1.2 四捨五入至小數點後 1 位
Math.round(d * 100.0) / 100.0; // 1.23 四捨五入至小數點後 2 位
Math.ceil(d * 1.0) / 1.0; // 2.0 無條件進位至小數點後 0 位
Math.ceil(d * 10.0) / 10.0; // 1.3 無條件進位至小數點後 1 位
Math.ceil(d * 100.0) / 100.0; // 1.24 無條件進位至小數點後 2 位
Math.floor(d * 1.0) / 1.0; // 1.0 無條件捨去至小數點後 0 位
Math.floor(d * 10.0) / 10.0; // 1.2 無條件捨去至小數點後 1 位
Math.floor(d * 100.0) / 100.0; // 1.23 無條件捨去至小數點後 2 位
有時候SSL連線不順,有錯誤訊息如下
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
可以使用 SSLPoke 進行測試
import java.io.PrintStream;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLPoke
{
public SSLPoke() {}
public static void main(String[] paramArrayOfString)
{
if (paramArrayOfString.length != 2) {
System.err.println("Utility to debug Java connections to SSL servers");
System.err.println("Usage: ");
System.err.println(" java " + SSLPoke.class.getName() + " <host> <port>");
System.err.println("or for more debugging:");
System.err.println(" java -Djavax.net.debug=ssl " + SSLPoke.class.getName() + " <host> <port>");
System.err.println();
System.err.println("Eg. to test the SSL certificate at https://localhost, use");
System.err.println(" java " + SSLPoke.class.getName() + " localhost 443");
System.exit(1);
}
try {
SSLSocketFactory localSSLSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket localSSLSocket = (SSLSocket)localSSLSocketFactory.createSocket(paramArrayOfString[0], Integer.parseInt(paramArrayOfString[1]));
java.io.InputStream localInputStream = localSSLSocket.getInputStream();
java.io.OutputStream localOutputStream = localSSLSocket.getOutputStream();
localOutputStream.write(1);
while (localInputStream.available() > 0) {
System.out.print(localInputStream.read());
}
System.out.println("Successfully connected");
System.exit(0);
}
catch (SSLHandshakeException localSSLHandshakeException) {
if (localSSLHandshakeException.getCause() != null) {
localSSLHandshakeException.getCause().printStackTrace();
} else {
localSSLHandshakeException.printStackTrace();
}
} catch (Exception localException) {
localException.printStackTrace();
}
System.exit(1);
}
}
編譯成 class
javac SSLPoke.java
執行測試
java SSLPoke vautht.xxx.com.tw 443
Successfully connected
下列 SQL 與 Java 資料類型目前支援輸入/輸出資料集與輸入/輸出參數。
在 Java 中常用到字串的處理,但 String 本身是固定長度不能改變內容的,我們常用 + 來連結附加字串其實相當耗費資源,在大量處理字串的情況下我們有更好的選擇。
Java 在 J2SE5.0 之後提供了 StringBuilder 類別,他有許多好用的操作字串的方法如:insert()、reverse()、replace()、append()等,更多詳細請看 API:java.lang.StringBuilder 的說明。
StringBuilder和StringBuffer有什麼差別呢?他們兩個提供了相同的介面,然而在不需考量多執行緒同步的時候我們使用 StringBuilder 來獲得最佳的效率,要考慮多執行緒的情況下使用 StringBuffer 來讓類別自動處理同步的問題。
找不到如何清空它嗎?看 method 時沒有看到叫做 clear() 之類的 method,其實我們可以
透過 delete(int start, int end)
這個 method 來達成目的,
用法就像這樣:stringBuffer.delete(0, stringBuffer.length())
。
問題說明:
Java 在訪問 SSL 加密的網站時,需要從 JDK 的 KeyStore 裡面查找相對應可信憑證書,如果不能從默認或者指定的 KeyStore 中找到可信憑證書,就會產生 javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 錯誤。
解決方法:
先匯出憑證書,通過 IE 瀏覽器打開相對於的網址,點擊安全姓報告,再點擊檢視憑證
點擊複製到檔案,匯出憑證書
匯入憑證書到 keystore,把憑證書 fielname_20220101-20221231.cer 放置 jdk security(/usr/local/jdk1.7.0_80/jre/lib/security) 目錄之下,以管理員身份進入對應的 jdk security 目錄之下。
執行下面的指令匯入憑證書
keytool -import -file fielname_20220101-20221231.cer -keystore cacerts -alias server
輸入金鑰儲存庫密碼:changeit
是否信任憑證書,輸入:Y
public String covertStackTraceToString(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
logger.error("A something error", e);
(1) 先說最近遇到一些特殊的狀況;
先前使用 Java WebServiceClient 呼叫伺服器提供的 API,後來呢伺服器的 SSL 憑證到期,當伺服器安裝新的 SSL 憑證之後,變成請求 SSL 不受 JDK 的信任。
出現以下 Exception:
org.jasig.cas.client.util.CommonUtils- sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.....
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.....
原因是 Java 的某些 JDK 版本無法辨識所謂的 [萬用憑證] 也就是 *.domain.com.tw 的憑證,既然 JDK 不認識它那我們就產生憑證書放入 JRE 的執行環境這樣就可以運行了。
(2) 建立一個名為 jssecacerts 的資料夾
(3) 把以下程式碼存檔為 InstallCert.java 放在 jssecacerts 資料夾裡面:
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}
System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();
System.out.println();
System.out.println(cert);
System.out.println();
System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}
(4) 在應用程式的主機上做編譯然後會產生 .class 檔,如下:
ServerName:/jssecacerts # javac InstallCert.java
ServerName:/jssecacerts # ls -l
-rw-r--r-- 1 root root 1123 Jan 22 10:32 InstallCert$SavingTrustManager.class
-rw-r--r-- 1 root root 5827 Jan 22 10:32 InstallCert.class
-rw-r--r-- 1 root root 6070 Jan 22 10:32 InstallCert.java
(5) 在應用程式的主機上執行 .class 檔,如下:
ServerName:/jssecacerts # java -classpath /jssecacerts InstallCert www.domain.com.tw:443
(6) 程式會在這裡暫停,請按 [ Enter ],最後會產生 jssecacerts 檔,如下:
ServerName:/jssecacerts # ls -l
-rw-r--r-- 1 root root 1123 Jan 22 10:32 InstallCert$SavingTrustManager.class
-rw-r--r-- 1 root root 5827 Jan 22 10:32 InstallCert.class
-rw-r--r-- 1 root root 6070 Jan 22 10:32 InstallCert.java
-rw-r--r-- 1 root root 103483 Feb 25 08:36 jssecacerts
(7) 把 jssecacerts 檔拷貝至 [JDK安裝的目錄]/jre/lib/security/ 之下,如下:
cp jssecacerts /usr/local/[JDK安裝的目錄]/jre/lib/security/